package cn.tedu.boot52.controller;

import cn.tedu.boot52.mapper.ImageMapper;
import cn.tedu.boot52.vo.Image;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class ImageController {

    @Autowired
    ImageMapper mapper;

    @RequestMapping("/upload")
    public void upload(Image image, MultipartFile picFile) throws IOException {
        System.out.println("info = " + image + ", picFile = " + picFile);

        //得到上传文件的原始文件名
        String fileName = picFile.getOriginalFilename();
        //得到后缀  a.jpg  .jpg   从.开始位置截取到末尾
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一的文件名  UUID代表唯一标识符
        fileName = UUID.randomUUID()+suffix;
        System.out.println(fileName);

        //准备保存图片的文件夹路径
        String dirPath = "D:/upload/";
        File dirFile = new File(dirPath);
        //如果文件对象不存在  则创建
        if (!dirFile.exists()){
            dirFile.mkdirs();  //创建文件夹(目录)
        }
        //得到文件的完整路径
        String filePath = dirPath+fileName;
        //把文件保存到上面的路径 异常抛出
        picFile.transferTo(new File(filePath));

        image.setUrl("/"+fileName);
        mapper.insert(image);
    }


    @RequestMapping("/select")
    public List<Image> select(){
        return mapper.select();
    }
}
